import React, { useState } from 'react';
import './Login.css';
import axios from 'axios';

function Login() {
    const [loginType, setLoginType] = useState('code'); // 'code' 或 'password'
    const [phone, setPhone] = useState('');
    const [verifyCode, setVerifyCode] = useState('');
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [errorMsg, setErrorMsg] = useState('');
    const [loading, setLoading] = useState(false);
    const [isAgreed, setIsAgreed] = useState(false);

    // 创建axios实例
    const createAxiosInstance = () => {
        const instance = axios.create({
            baseURL: 'http://localhost:8080',
            timeout: 10000,
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Origin': window.location.origin
            },
            withCredentials: true
        });

        // 添加响应拦截器
        instance.interceptors.response.use(
            response => response,
            error => {
                console.error('请求错误:', error);
                return Promise.reject(error);
            }
        );

        return instance;
    };

    // 账号密码登录
    const handlePasswordLogin = async (e) => {
        e.preventDefault();
        if (!username) {
            setErrorMsg('请输入账号');
            return;
        }
        if (!password) {
            setErrorMsg('请输入密码');
            return;
        }
        if (!isAgreed) {
            setErrorMsg('请同意隐私政策');
            return;
        }

        try {
            setLoading(true);
            setErrorMsg('');
            
            console.log('尝试账号登录，用户名:', username);
            
            try {
                // 尝试正常登录
                const instance = createAxiosInstance();
                const response = await instance.post('/auth/login', {
                    username,
                    password
                });
                
                console.log('登录响应:', response);
                
                if (response.data.code === 200) {
                    handleLoginSuccess(response.data.data);
                    return;
                } else {
                    throw new Error(response.data.message || '登录失败');
                }
            } catch (apiError) {
                console.error('API登录失败:', apiError);
                
                // 如果是测试账号，进行本地模拟登录（仅用于演示）
                if (username === 'admin' && password === '123456') {
                    console.log('使用模拟数据登录');
                    
                    // 模拟登录成功的数据
                    const mockTokenData = {
                        token: 'mock_token_12345',
                        username: 'admin',
                        nickname: '管理员',
                        avatar: 'https://avatars.githubusercontent.com/u/1?v=4'
                    };
                    
                    handleLoginSuccess(mockTokenData);
                    return;
                }
                
                // 如果不是测试账号或者其他错误，抛出错误
                throw apiError;
            }
        } catch (error) {
            console.error('登录失败:', error);
            let errorMessage = '登录失败，请稍后重试';
            
            if (error.response) {
                console.error('错误状态码:', error.response.status);
                console.error('错误数据:', error.response.data);
                errorMessage = error.response.data?.message || `服务器错误: ${error.response.status}`;
            } else if (error.message) {
                errorMessage = error.message;
            }
            
            setErrorMsg(errorMessage);
        } finally {
            setLoading(false);
        }
    };

    // 验证码登录
    const handleCodeLogin = async (e) => {
        e.preventDefault();
        if (!phone) {
            setErrorMsg('请输入手机号');
            return;
        }
        if (!verifyCode) {
            setErrorMsg('请输入验证码');
            return;
        }
        if (!isAgreed) {
            setErrorMsg('请同意隐私政策');
            return;
        }

        try {
            setLoading(true);
            setErrorMsg('');
            
            console.log('尝试验证码登录，手机号:', phone);
            
            try {
                // 尝试正常登录
                const instance = createAxiosInstance();
                const response = await instance.post('/auth/login/code', {
                    phone,
                    code: verifyCode
                });
                
                console.log('登录响应:', response);
                
                if (response.data.code === 200) {
                    handleLoginSuccess(response.data.data);
                    return;
                } else {
                    throw new Error(response.data.message || '验证码登录失败');
                }
            } catch (apiError) {
                console.error('API登录失败:', apiError);
                
                // 如果是测试手机号，进行本地模拟登录（仅用于演示）
                if (phone === '13800138000' && verifyCode === '123456') {
                    console.log('使用模拟数据登录');
                    
                    // 模拟登录成功的数据
                    const mockTokenData = {
                        token: 'mock_token_phone_12345',
                        phone: '13800138000',
                        nickname: '测试用户',
                        avatar: 'https://avatars.githubusercontent.com/u/2?v=4'
                    };
                    
                    handleLoginSuccess(mockTokenData);
                    return;
                }
                
                // 如果不是测试账号或者其他错误，抛出错误
                throw apiError;
            }
        } catch (error) {
            console.error('登录失败:', error);
            let errorMessage = '登录失败，请稍后重试';
            
            if (error.response) {
                console.error('错误状态码:', error.response.status);
                console.error('错误数据:', error.response.data);
                errorMessage = error.response.data?.message || `服务器错误: ${error.response.status}`;
            } else if (error.message) {
                errorMessage = error.message;
            }
            
            setErrorMsg(errorMessage);
        } finally {
            setLoading(false);
        }
    };

    const handleSendVerifyCode = async () => {
        if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
            setErrorMsg('请输入正确的手机号');
            return;
        }

        try {
            setLoading(true);
            setErrorMsg('');
            
            console.log('尝试发送验证码，手机号:', phone);
            
            try {
                // 尝试发送真实验证码
                const instance = createAxiosInstance();
                const response = await instance.post('/auth/code/send', {
                    phone
                });
                
                console.log('发送验证码响应:', response);
                
                if (response.data.code === 200) {
                    setErrorMsg('验证码已发送，请注意查收');
                    return;
                } else {
                    throw new Error(response.data.message || '发送验证码失败');
                }
            } catch (apiError) {
                console.error('API发送验证码失败:', apiError);
                
                // 对任何手机号都模拟发送成功（仅用于演示）
                setErrorMsg('验证码已发送（模拟），请使用123456');
                return;
            }
        } catch (error) {
            console.error('发送验证码失败:', error);
            let errorMessage = '发送验证码失败，请稍后重试';
            
            if (error.response) {
                console.error('错误状态码:', error.response.status);
                console.error('错误数据:', error.response.data);
                errorMessage = error.response.data?.message || `服务器错误: ${error.response.status}`;
            } else if (error.message) {
                errorMessage = error.message;
            }
            
            setErrorMsg(errorMessage);
        } finally {
            setLoading(false);
        }
    };

    // 测试后端API连接
    const testBackendAPI = async () => {
        try {
            setLoading(true);
            setErrorMsg('');
            
            console.log('测试后端API连接');
            
            // 使用fetch API直接请求后端
            const response = await fetch('http://localhost:8080/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'Origin': window.location.origin
                },
                body: JSON.stringify({
                    username: 'admin',
                    password: '123456'
                })
            });
            
            console.log('测试响应状态:', response.status);
            
            if (response.ok) {
                const data = await response.json();
                console.log('测试响应数据:', data);
                setErrorMsg('后端API连接正常，响应码: ' + response.status);
            } else {
                setErrorMsg(`后端API连接失败，响应码: ${response.status}`);
            }
        } catch (error) {
            console.error('API测试失败:', error);
            setErrorMsg(`API测试失败: ${error.message}`);
        } finally {
            setLoading(false);
        }
    };
    
    // 修改handleLoginSuccess，正确处理登录成功后的跳转
    const handleLoginSuccess = (tokenData) => {
        // 保存登录信息到localStorage
        localStorage.setItem('token', tokenData.token);
        localStorage.setItem('user', JSON.stringify({
            username: tokenData.username || tokenData.phone,
            nickname: tokenData.nickname,
            avatar: tokenData.avatar
        }));
        
        // 显示提示信息
        setErrorMsg('登录成功，正在跳转...');
        
        // 跳转到home页面
        setTimeout(() => {
            // 检查是否有/home路由，如果没有就跳转到根路径
            if (window.location.pathname.includes('/home')) {
                window.location.href = '/home';
            } else {
                window.location.href = '/';  // 默认跳转到根路径
            }
        }, 1000);  // 延迟1秒跳转，让用户看到提示信息
    };

    // 切换登录方式
    const toggleLoginType = () => {
        setLoginType(loginType === 'code' ? 'password' : 'code');
        setErrorMsg('');
    };

    return (
        <div className="login-container">
            <div className="login-form">
                <h2 className="login-title">登录</h2>
                
                {errorMsg && <div className="error-message">{errorMsg}</div>}
                
                {loginType === 'code' ? (
                    // 验证码登录表单
                    <form onSubmit={handleCodeLogin}>
                        <div className="form-item">
                            <input 
                                type="tel" 
                                placeholder="手机号码" 
                                value={phone}
                                onChange={(e) => setPhone(e.target.value)}
                                disabled={loading}
                            />
                        </div>
                        <div className="form-item verify-code-container">
                            <input 
                                type="text" 
                                placeholder="6位验证码" 
                                value={verifyCode}
                                onChange={(e) => setVerifyCode(e.target.value)}
                                disabled={loading}
                            />
                            <button 
                                type="button" 
                                className="send-code-btn"
                                onClick={handleSendVerifyCode}
                                disabled={loading}
                            >
                                获取验证码
                            </button>
                        </div>

                        <button 
                            type="submit" 
                            className="login-btn"
                            disabled={loading || !isAgreed}
                        >
                            {loading ? '登录中...' : '登录'}
                        </button>
                    </form>
                ) : (
                    // 账号密码登录表单
                    <form onSubmit={handlePasswordLogin}>
                        <div className="form-item">
                            <input 
                                type="text" 
                                placeholder="账号/用户名" 
                                value={username}
                                onChange={(e) => setUsername(e.target.value)}
                                disabled={loading}
                            />
                        </div>
                        <div className="form-item">
                            <input 
                                type="password" 
                                placeholder="密码" 
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                disabled={loading}
                            />
                        </div>

                        <button 
                            type="submit" 
                            className="login-btn"
                            disabled={loading || !isAgreed}
                        >
                            {loading ? '登录中...' : '登录'}
                        </button>
                    </form>
                )}

                <div className="password-login" onClick={toggleLoginType}>
                    {loginType === 'code' ? '密码登录' : '验证码登录'}
                </div>

                {/* 添加测试后端按钮 */}
                <div className="test-api-btn" onClick={testBackendAPI}>
                    测试后端接口
                </div>

                <div className="other-login">
                    <div className="divider">
                        <span>或通过以下方式登录</span>
                    </div>
                    <div className="other-login-icons">
                        <div className="third-party-icon alipay">
                            <img src="	https://cdn8.axureshop.com/demo2025/2175334/images/%E5%85%8D%E5%AF%86%E7%99%BB%E5%BD%95/u1900.svg" alt="支付宝" />
                        </div>
                        <div className="third-party-icon taobao">
                            <img src="	https://cdn8.axureshop.com/demo2025/2175334/images/%E5%85%8D%E5%AF%86%E7%99%BB%E5%BD%95/u1898.svg" alt="淘宝" />
                        </div>
                        <div className="third-party-icon wechat">
                            <img src="https://cdn8.axureshop.com/demo2025/2175334/images/%E5%85%8D%E5%AF%86%E7%99%BB%E5%BD%95/u1892.svg" alt="微信" />
                        </div>
                        <div className="third-party-icon qq">
                            <img src="https://cdn8.axureshop.com/demo2025/2175334/images/%E5%85%8D%E5%AF%86%E7%99%BB%E5%BD%95/u1896.svg" alt="QQ" />
                        </div>
                        <div className="third-party-icon weibo">
                            <img src="https://cdn8.axureshop.com/demo2025/2175334/images/%E5%85%8D%E5%AF%86%E7%99%BB%E5%BD%95/u1896.svg" alt="微博" />
                        </div>
                    </div>
                </div>

                <div className="agreement">
                    <label className="checkbox-label">
                        <input
                            type="checkbox"
                            checked={isAgreed}
                            onChange={(e) => setIsAgreed(e.target.checked)}
                        />
                        <span>我已阅读并同意</span>
                        <a href="/privacy" className="privacy-link">《种草平台隐私政策》</a>
                    </label>
                </div>
            </div>
        </div>
    );
}

export default Login; 